package eu.briano.suirvellancecamera;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.OutputStream;
import android.graphics.Bitmap;
import android.graphics.YuvImage;
import android.widget.Toast;




public class AlarmNotifier {
	static long lastAlarm = Utils.now()+Utils.minSendElapse*10;
	static long sending = 0;
	
	private SuirvellanceCameraActivity a;


	public AlarmNotifier(SuirvellanceCameraActivity _a) {
		a = _a;
	}

	public void sendAlarm(byte [] buffer, int previewFormat, int bW, int bH, Bitmap debugMap ,String debugInfo) {

		
		try {
			if ( (Utils.now() <lastAlarm)   ||  sending > Utils.maxSendingFile  ) {
				Log.v(Utils.logName,"AlarmNotifier skip alarm");
				a.runOnUiThread(new Runnable() {
					public void run() {
						Toast.makeText(a.getApplicationContext(), R.string.alarm_skipped, 100).show();
					}
				});				
				return;
			}
			a.runOnUiThread(new Runnable() {
				public void run() {
					Toast.makeText(a.getApplicationContext(), R.string.alarm, 100).show();
				}
			});
			lastAlarm = Utils.now()+Utils.minSendElapse;
			
			new File(Utils.getWorkBasePath()).mkdirs();
			new File(Utils.getSendFileBasePath()).mkdirs();
			
			long now = Utils.now();

			
			YuvImage saveImage = new YuvImage(buffer, Utils.previewFormat, bW, bH, null);
			
			
			String fileName = Utils.formattedTimestamp(now);
			String completeFileName =  Utils.getWorkBasePath()+ fileName;
			
			Utils.saveImage(saveImage,completeFileName);
			File destFile = new File(Utils.getSendFileBasePath() + fileName);
			File srcFile = new File(completeFileName);
			srcFile.renameTo(destFile);
			
			
			fileName = Utils.formattedTimestamp(now)+".map";
			completeFileName = Utils.getWorkBasePath()+fileName;
			
			File file = new File(completeFileName);
			OutputStream stream  = new FileOutputStream(file );
			debugMap.compress(Bitmap.CompressFormat.JPEG, 100, stream );
			stream.close();
			
			destFile = new File(Utils.getSendFileBasePath() + fileName);
			file.renameTo(destFile);
			
			fileName = Utils.formattedTimestamp(now)+".txt";
			file = new File(Utils.getWorkBasePath()+fileName);
			FileWriter writer = new  FileWriter(file);
			writer.write(debugInfo);
			writer.flush();
			writer.close();
			destFile = new File(Utils.getSendFileBasePath() + fileName);
			file.renameTo(destFile);
			
			
			

		} catch (Exception e) {
			Log.e(Utils.logName, "AlarmNotifier error ",e);
		}
	}

	
}

